﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Utility;
using System.Data.SqlClient;
using System.Text;
using VAdvantage.Model;
using System.Data;
using VAdvantage.Classes;
using VAdvantage.DataBase;
using System.Threading;
using System.Windows.Threading;
using VAdvantage.DataService;
using System.Collections;
using System.Collections.ObjectModel;
using System.Reflection;
using VAdvantage.Search;
using SilverlightDesktop.Controls;
using System.Windows.Data;

/* 1-> Info improvement- Change Request (CR_01)
 * Call Info Classes from Project(Partner Kit)
 * 
 * 2->Change Request (CR_02)
 * Forcefully perform Callout to Set Other Column Values(e.g Lot No for US Client) 
 */

namespace VAdvantage.Framework
{
    public abstract partial class Info : ChildWindow
    {
        protected const int HEIGHT = 23;

        /** Master (owning) Window  */
        protected int _WindowNo;
        /** Table Name              */
        protected String _tableName;
        /** Key Column Name         */
        protected String _keyColumn;
        /** Enable more than one selection  */
        protected bool _multiSelection;
        /** Initial WHERE Clause    */
        protected String _whereClause = "";

        /** Main SQL Statement      */
        String _sqlMain;
        /** Count SQL Statement		*/
        private String _sqlCount;
        /** Order By Clause         */
        String _sqlOrder;

        private int _keyColumnIndex = -1;

        /** Cancel pressed - need to differentiate between OK - Cancel - Exit	*/
        private bool _cancel = false;

        /** OK pressed                  */
        private bool _ok = false;

        protected abstract Info_Column[] GetInfoColumns();

        protected Info_Column[] _Layout;

        protected bool _LoadedOK = false;

        /**	Logger			*/
        protected VLogger log = null;

        /*Change Request (CR_02)*/
        protected bool forceResetValue = false;

        List<object> selectedRows = new List<object>();

        public bool updating = false;

        public bool viewProd = false;


        public Info(Object frame, bool modal, int WindowNo, String tableName, String keyColumn, bool multiSelection, String whereClause)
        {

            log = VLogger.GetVLogger(this.GetType().FullName);
            log.Info("WinNo=" + _WindowNo + " " + whereClause);

            _WindowNo = WindowNo;
            _tableName = tableName;
            _keyColumn = keyColumn;
            _multiSelection = multiSelection;

            if (whereClause == null || whereClause.IndexOf('@') == -1)
                _whereClause = whereClause;
            else
            {
                _whereClause = Utility.Envs.ParseContext(Envs.GetContext(), _WindowNo, whereClause, false, false);
                if (_whereClause.Length == 0)
                    log.Log(Level.SEVERE, "Cannot parse context= " + whereClause);
            }



            Init();

            if (Util.GetValueOfInt(Envs.GetCtx().GetContext(_WindowNo, Envs.GetCtx().GetContext(_WindowNo, 1, "KeyColumnName"))) != 0)
            {
                updating = true;
            }

            if (keyColumn.ToUpper() == "M_PRODUCT_ID" && multiSelection && !updating)
            {
                bShowSaved.Visibility = Visibility.Visible;
                if (InfoLines.PQ.Count > 0)
                {
                    bShowSaved.IsEnabled = true;
                }
                else
                {
                    bShowSaved.IsEnabled = false;
                }
                bClose.Visibility = Visibility.Visible;
            }
            else
            {
                bClose.Visibility = Visibility.Collapsed;
            }
            bShowSaved.Click += new RoutedEventHandler(bShowSaved_Click);
            bClose.Click += new RoutedEventHandler(bClose_Click);
            bOK.Click += new RoutedEventHandler(bOK_Click);
            CancelButton.Click += new RoutedEventHandler(CancelButton_Click);
            bRefresh.Click += new RoutedEventHandler(bRefresh_Click);
            bPrint.Visibility = System.Windows.Visibility.Collapsed;
            //bCancel.Click += new RoutedEventHandler(bCancel_Click);
            vdgvRecords.CellEditEnded += new EventHandler<DataGridCellEditEndedEventArgs>(vdgvRecords_CellEditEnded);
            vdgvRecords.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(vdgvRecords_AutoGeneratingColumn);
            vdgvRecords.LoadingRow += new EventHandler<DataGridRowEventArgs>(vdgvRecords_LoadingRow);
            vdgvRecords.PreparingCellForEdit += new EventHandler<DataGridPreparingCellForEditEventArgs>(vdgvRecords_PreparingCellForEdit);
            vdgvRecords2.CurrentCellChanged += new EventHandler<EventArgs>(vdgvRecords2_CurrentCellChanged);
            vdgvRecords2.LoadingRow += new EventHandler<DataGridRowEventArgs>(vdgvRecords2_LoadingRow);
            vdgvRecords2.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(vdgvRecords2_AutoGeneratingColumn);

            ToolTipService.SetToolTip((System.Windows.Controls.Button)bClose, Msg.GetMsg(Envs.GetCtx(), "AddToList"));
            ToolTipService.SetToolTip((System.Windows.Controls.Button)bOK, Msg.GetMsg(Envs.GetCtx(), "Done"));
            ToolTipService.SetToolTip((System.Windows.Controls.Button)CancelButton, Msg.GetMsg(Envs.GetCtx(), "Cancel"));
            ToolTipService.SetToolTip((System.Windows.Controls.Button)bShowSaved, Msg.GetMsg(Envs.GetCtx(), "ViewSavedProducts"));
        }

        void vdgvRecords2_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (vdgvRecords2.Columns.Count > 4)
            {
                vdgvRecords2.Columns[2].IsReadOnly = true;
                vdgvRecords2.Columns[4].IsReadOnly = true;
                vdgvRecords2.Columns[1].Visibility = Visibility.Collapsed;
                vdgvRecords2.Columns[4].Visibility = Visibility.Collapsed;


                DataGridColumn col = vdgvRecords2.Columns[3];
                col.CellStyle = (Style)Resources["DataGridCellStyle"];
            }
        }

        void vdgvRecords2_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            if (vdgvRecords2.Columns.Count > 5)
            {
                vdgvRecords2.Columns[5].IsReadOnly = true;
                vdgvRecords2.Columns[0].DisplayIndex = 5;
            }
            e.Row.Background = new SolidColorBrush(Color.FromArgb(255, 237, 241, 244));
        }

        void vdgvRecords2_CurrentCellChanged(object sender, EventArgs e)
        {
            if ((((System.Windows.Controls.DataGrid)sender).SelectedItem) != null)
            {
                int x = ((SavedProducts)(((System.Windows.Controls.DataGrid)sender).SelectedItem)).SrNo;

                PagedCollectionView pv = vdgvRecords2.ItemsSource as PagedCollectionView;
                object[] pqtyAll = VAdvantage.Classes.InfoLines.PQ.ToArray();

                if (pqtyAll.Length > x)
                {
                    object f = pqtyAll.GetValue(x);
                    Dictionary<int, Decimal> pq = ((VAdvantage.Classes.InfoLines)f)._prodQty;
                    List<int> key = pq.Keys.ToList();
                    pq[Util.GetValueOfInt(Util.GetValueOfInt(key[0]))] = ((SavedProducts)(((System.Windows.Controls.DataGrid)sender).SelectedItem)).QtyEntered;
                    ((InfoLines)VAdvantage.Classes.InfoLines.PQ[x])._prodQty = pq;

                }
                else if (pqtyAll.Length == 1)
                {
                    object f = pqtyAll.GetValue(0);
                    Dictionary<int, Decimal> pq = ((VAdvantage.Classes.InfoLines)f)._prodQty;
                    List<int> key = pq.Keys.ToList();
                    pq[Util.GetValueOfInt(Util.GetValueOfInt(key[0]))] = ((SavedProducts)(((System.Windows.Controls.DataGrid)sender).SelectedItem)).QtyEntered;
                    ((InfoLines)VAdvantage.Classes.InfoLines.PQ[0])._prodQty = pq;
                }
                if (pv.Count == 0)
                {
                    bShowSaved.IsEnabled = false;
                }
            }
            else
            {
                bShowSaved.IsEnabled = false;
            }
        }

        ObservableCollection<SavedProducts> svPrd = null;
        void bShowSaved_Click(object sender, RoutedEventArgs e)
        {
            BusyWindow.IsBusy = true;
            svPrd = new ObservableCollection<SavedProducts>();
            vdgvRecords2.Visibility = Visibility.Visible;
            vdgvRecords.Visibility = Visibility.Collapsed;
            viewProd = true;

            DataSet dsProd = null;
            bClose.Visibility = Visibility.Collapsed;

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {


                object[] pqtyAll = VAdvantage.Classes.InfoLines.PQ.ToArray();
                Dictionary<int, Decimal> ProductQty = new Dictionary<int, decimal>();
                List<int> prodID = new List<int>();
                List<Decimal> qty = new List<decimal>();
                List<string> prodName = new List<string>();
                List<string> uom = new List<string>();

                for (int x = 0; x < pqtyAll.Length; x++)
                {
                    object f = pqtyAll.GetValue(x);
                    Dictionary<int, Decimal> pq = ((VAdvantage.Classes.InfoLines)f)._prodQty;
                    List<int> key = pq.Keys.ToList();

                    prodID.Add(Util.GetValueOfInt(key[0]));
                    qty.Add(Convert.ToDecimal(pq[Util.GetValueOfInt(Util.GetValueOfInt(key[0]))]));
                    string sqlaa = "select p.name as Product, u.name as UOM from m_product p left outer  join c_uom u on (u.c_uom_id = p.c_uom_id) where p.m_product_id = " + Util.GetValueOfInt(key[0]);
                    DataSet dspu = DB.ExecuteDataset(sqlaa, null, null);
                    if (dspu != null)
                    {
                        prodName.Add(Util.GetValueOfString(dspu.Tables[0].Rows[0][0]));
                        uom.Add(Util.GetValueOfString(dspu.Tables[0].Rows[0][1]));
                    }
                }


                Dispatcher.BeginInvoke(delegate
                {
                    if (prodID.Count > 0)
                    {
                        SavedProducts prd = null;
                        for (int i = 0; i < prodID.Count; i++)
                        {
                            prd = new SavedProducts();
                            prd.SrNo = i;
                            prd.Product = prodName[i];
                            prd.QtyEntered = qty[i];
                            prd.UOM = uom[i];
                            prd.M_Product_ID1 = prodID[i];
                            // prd.Delete = Envs.LoadImageSource("yellow.png");
                            svPrd.Add(prd);
                        }

                        BindGridSavedProducts();
                        BusyWindow.IsBusy = false;
                    }
                });

            });
        }

        private void BindGridSavedProducts()
        {
            PagedCollectionView pgv = new PagedCollectionView(svPrd);
            vdgvRecords2.AutoGenerateColumns = true;
            vdgvRecords2.ItemsSource = pgv;

            vdgvRecords2.LoadingRow += (se, ev) =>
            {
                DataGridRow row = ev.Row;
                foreach (DataGridColumn col in vdgvRecords2.Columns)
                {
                    FrameworkElement cellContent = col.GetCellContent(ev.Row);
                    Image gridBtn = cellContent as Image;
                    if (gridBtn != null)
                    {
                        gridBtn.MouseLeftButtonDown -= gridBtn_MouseLeftButtonDown;
                        gridBtn.MouseLeftButtonDown += new MouseButtonEventHandler(gridBtn_MouseLeftButtonDown);
                    }
                }

                //vdgvRecords2.Columns[2].IsReadOnly = true;
                //vdgvRecords2.Columns[4].IsReadOnly = true;

            };
        }

        void gridBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image btn = sender as Image;
            object aa = btn.DataContext;

            PagedCollectionView pv = vdgvRecords2.ItemsSource as PagedCollectionView;
            for (int i = 0; i < pv.Count; i++)
            // for (int i = 0; i < svPrd.Count; i++)
            {
                if (((SavedProducts)svPrd[i]).SrNo == ((SavedProducts)aa).SrNo)
                {
                    InfoLines.PQ.RemoveAt(i);
                    svPrd.RemoveAt(i);
                    break;
                }
            }
            for (int i = 0; i < svPrd.Count; i++)
            {
                ((SavedProducts)svPrd[i]).SrNo = i;
            }

            BindGridSavedProducts();

            //PagedCollectionView pgv = new PagedCollectionView(svPrd);
            //vdgvRecords2.AutoGenerateColumns = true;
            //vdgvRecords2.ItemsSource = pgv;
            //vdgvRecords2.LoadingRow += (se, ev) =>
            //{

            //    DataGridRow row = ev.Row;
            //    foreach (DataGridColumn col in vdgvRecords2.Columns)
            //    {
            //        FrameworkElement cellContent = col.GetCellContent(ev.Row);
            //        Image gridBtn = cellContent as Image;
            //        if (gridBtn != null)
            //        {
            //            gridBtn.MouseLeftButtonDown -= gridBtn_MouseLeftButtonDown;
            //            gridBtn.MouseLeftButtonDown += new MouseButtonEventHandler(gridBtn_MouseLeftButtonDown);
            //        }
            //    }

            //    vdgvRecords2.Columns[2].IsReadOnly = true;
            //    vdgvRecords2.Columns[4].IsReadOnly = true;
            //    vdgvRecords2.Columns[1].Visibility = Visibility.Collapsed;
            //    vdgvRecords2.Columns[5].Visibility = Visibility.Collapsed;

            //};
        }

        void vdgvRecords_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {

        }

        void vdgvRecords_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Background = new SolidColorBrush(Color.FromArgb(255, 237, 241, 244));
        }

        void vdgvRecords_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (_keyColumn.ToUpper() == "M_PRODUCT_ID")
            {
                if (vdgvRecords.Columns.Count >= 16)
                {
                    vdgvRecords.Columns[0].IsReadOnly = true;
                    vdgvRecords.Columns[1].IsReadOnly = true;
                    vdgvRecords.Columns[2].IsReadOnly = true;
                    vdgvRecords.Columns[3].IsReadOnly = true;
                    vdgvRecords.Columns[4].IsReadOnly = true;
                    vdgvRecords.Columns[6].IsReadOnly = true;
                    vdgvRecords.Columns[7].IsReadOnly = true;
                    vdgvRecords.Columns[8].IsReadOnly = true;
                    vdgvRecords.Columns[9].IsReadOnly = true;
                    vdgvRecords.Columns[10].IsReadOnly = true;
                    vdgvRecords.Columns[11].IsReadOnly = true;
                    vdgvRecords.Columns[12].IsReadOnly = true;
                    vdgvRecords.Columns[13].IsReadOnly = true;
                    vdgvRecords.Columns[14].IsReadOnly = true;
                    vdgvRecords.Columns[15].IsReadOnly = true;
                   // vdgvRecords.Columns[16].IsReadOnly = true;
                    //vdgvRecords.Columns[17].IsReadOnly = true;

                    if (_multiSelection && !updating)
                    {
                        vdgvRecords.Columns[5].IsReadOnly = false;
                    }
                    else
                    {
                        vdgvRecords.Columns[5].IsReadOnly = true;
                        vdgvRecords.Columns[5].Visibility = Visibility.Collapsed;
                    }
                    vdgvRecords.Columns[2].Visibility = Visibility.Collapsed;

                    DataGridColumn col = vdgvRecords.Columns[5];
                    col.CellStyle = (Style)Resources["DataGridCellStyle"];


                }
            }
        }

        void vdgvRecords_CellEditEnded(object sender, DataGridCellEditEndedEventArgs e)
        {
            if (_keyColumn.ToUpper() == "M_PRODUCT_ID")
            {
                if (selectedRows.Contains(vdgvRecords.SelectedItem))
                {
                    selectedRows.Remove(vdgvRecords.SelectedItem);
                    selectedRows.Add(vdgvRecords.SelectedItem);
                }
                else
                {
                    selectedRows.Add(vdgvRecords.SelectedItem);
                }
            }
        }

        DataServiceBasic2.DataServicesBasic2Client ser = null;

        void bClose_Click(object sender, RoutedEventArgs e)
        {
            string[] zzz = Envs.GetCtx().GetEntireContext();

            for (int k = 0; k < selectedRows.Count; k++)
            {
                vdgvRecords.SelectedItems.Add(selectedRows[k]);
            }
            _ok = true;
            SaveSelection();
            if (InfoLines.PQ.Count > 0)
            {
                bShowSaved.IsEnabled = true;
            }
            else
            {
                bShowSaved.IsEnabled = false;
            }
            selectedRows.RemoveRange(0, selectedRows.Count);

            //this.DialogResult = true;
        }



        protected virtual void bRefresh_Click(object sender, RoutedEventArgs e)
        {
            viewProd = false;
            if (_keyColumn.ToUpper() == "M_PRODUCT_ID" && _multiSelection && !updating)
            {
                bClose.Visibility = Visibility.Visible;
            }
            vdgvRecords2.Visibility = Visibility.Collapsed;
            vdgvRecords.Visibility = Visibility.Visible;
            ExecuteQuery();
        }

        public void SetStatusMsg(string msg)
        {
            Dispatcher.BeginInvoke(delegate
            {
                statusBar.Text = msg;
            });
        }


        public bool GetForceResetValue()
        {
            return forceResetValue;
        }

        /// <summary>
        /// Sets the title for Info Window
        /// </summary>
        /// <param name="title"></param>
        public void SetTitle(String title)
        {
            this.Title = Utility.Util.CleanMnemonic(title);
        }

        void bOK_Click(object sender, RoutedEventArgs e)
        {
            if (_keyColumn != null && _keyColumn.ToUpper() != "M_PRODUCT_ID")
            {
                _ok = true;
                SaveSelection();
                this.DialogResult = true;
            }
            else
            {
                if (_multiSelection && !updating)
                {
                    object[] pqtyAll = VAdvantage.Classes.InfoLines.PQ.ToArray();

                    
                    if (pqtyAll.Length > 0)
                    {
                        SaveProducts(pqtyAll);
                        
                    }
                    else
                    {
                        Envs.GetCtx().SetContext("Single", true);
                        _ok = true;
                        SaveSelection();
                        pqtyAll = VAdvantage.Classes.InfoLines.PQ.ToArray();

                        if (pqtyAll.Length > 0)
                        {
                            SaveProducts(pqtyAll);
                            
                        }
                    }
                }
                else
                {
                    _ok = true;
                    SaveSelection();
                    //this.DialogResult = true;
                }
                this.DialogResult = true;
            }

            //do not use this.Close(), this function may keep parent window disable even after ths wondow is closed
            //this.Close();

            //   this.DialogResult = true;
        }

        private void SaveProducts(object[] pqtyAll)
        {
            string recordID = Envs.GetCtx().GetContext(_WindowNo, Envs.GetCtx().GetContext(_WindowNo, 0, "KeyColumnName"));
            string keycolName = Envs.GetCtx().GetContext(_WindowNo, 0, "KeyColumnName");

            string lineID = Envs.GetCtx().GetContext(_WindowNo, Envs.GetCtx().GetContext(_WindowNo, 1, "KeyColumnName"));
            string lineName = Envs.GetCtx().GetContext(_WindowNo, 1, "KeyColumnName");

            int M_Locator_ID = Util.GetValueOfInt(Envs.GetCtx().GetContext(_WindowNo, 1, "M_Locator_ID"));

            int id = Util.GetValueOfInt(recordID);
            int lineid = Util.GetValueOfInt(lineID);

            // object[] pqtyAll = VAdvantage.Classes.InfoLines.PQ.ToArray();
            Dictionary<int, Decimal> ProductQty = new Dictionary<int, decimal>();
            List<int> prod = new List<int>();
            List<Decimal> qty = new List<decimal>();

            for (int x = 0; x < pqtyAll.Length; x++)
            {
                object f = pqtyAll.GetValue(x);
                Dictionary<int, Decimal> pq = ((VAdvantage.Classes.InfoLines)f)._prodQty;
                List<int> key = pq.Keys.ToList();

                prod.Add(Util.GetValueOfInt(key[0]));
                qty.Add(Convert.ToDecimal(pq[Util.GetValueOfInt(Util.GetValueOfInt(key[0]))]));
                if (lineid != 0)
                {
                    break;
                }
            }


            ser = AEnv.GetDataServiceBasic2Client();
            //ser = new DataServiceBasic2.DataServicesBasic2Client();
            // client.GetDataXmlFromExcelCompleted += new EventHandler<DataServiceBasic2.GetDataXmlFromExcelCompletedEventArgs>(client_GetDataXmlFromExcelCompleted);


            ser.SetProductQtyAsync(id, keycolName, prod, qty, lineid, (Dictionary<string, string>)Envs.GetCtx().GetMap());

            ser.SetProductQtyCompleted += new EventHandler<DataServiceBasic2.SetProductQtyCompletedEventArgs>(ser_SetProductQtyCompleted);
            //VAdvantage.Apps.APanel ap = new Apps.APanel();

            VAdvantage.Classes.InfoLines.PQ.Clear();
            Envs.GetCtx().SetContext("Single", false);
        }

        void ser_SetProductQtyCompleted(object sender, DataServiceBasic2.SetProductQtyCompletedEventArgs e)
        {

            ser.CloseAsync();
        }

        /// <summary>
        /// Gets the selected row key from data grid view.
        /// </summary>
        /// <returns></returns>
        protected int? GetSelectedRowKey()
        {
            int row = vdgvRecords.SelectedIndex;
            if (row != -1 && _keyColumnIndex != -1)
            {
                object data = null;
                var type = vdgvRecords.SelectedItem.GetType();
                PropertyInfo objPropInfo = type.GetProperty(_Layout[_keyColumnIndex].GetColHeader());
                if (objPropInfo != null)
                {
                    data = objPropInfo.GetValue(vdgvRecords.SelectedItem, null);
                    if (data.GetType() == typeof(IDColumn))
                    {
                        data = ((IDColumn)data).GetRecord_ID();
                        return (int)data;
                    }
                    else if (data.GetType() == typeof(Int32))
                        return (int)data;
                }
                //IEnumerable<IDictionary> dic = data as IEnumerable<IDictionary>;
                //DataUtil.DataObject currentRow = (DataUtil.DataObject)selected[0];

            }

            return null;
        }

        protected Object[] GetSelectedRowKeys()
        {
            System.Collections.ArrayList selectedDataList = new System.Collections.ArrayList();


            if (_keyColumnIndex == -1)
            {
                return selectedDataList.ToArray();
            }

            if (_multiSelection)
            {


                int rows = vdgvRecords.SelectedItems.Count;
                for (int row = 0; row < rows; row++)
                {
                    // If this is the Totals row (last row), we need to skip it - teo_sarca [ 2860556 ]
                    //if (p_table.getShowTotals() && row == rows - 1)
                    if (row == rows - 1)
                    {
                        //continue;
                    }

                    object data = null;
                    var type = vdgvRecords.SelectedItems[row].GetType();
                    PropertyInfo objPropInfo = type.GetProperty(_Layout[_keyColumnIndex].GetColHeader());

                    //******************************* Change **************************//
                    PropertyInfo objPropInfo1 = type.GetProperty(_Layout[5].GetColHeader());
                    object data1 = objPropInfo1.GetValue(vdgvRecords.SelectedItems[row], null);
                    if (Util.GetValueOfDecimal(data1) > 0)
                    {
                        if (objPropInfo != null)
                        {
                            data = objPropInfo.GetValue(vdgvRecords.SelectedItems[row], null);
                            //    if (data.GetType() == typeof(IDColumn))
                            //    {
                            //        data = ((IDColumn)data).GetRecord_ID();
                            //        selectedDataList.Add((int)data);
                            //    }
                            //    else if (data.GetType() == typeof(Int32))
                            //        selectedDataList.Add((int)data);
                            //}

                            if (data.GetType() == typeof(IDColumn))
                            {
                                IDColumn dataColumn = (IDColumn)data;
                                // if (dataColumn.IsSelected())
                                // {
                                selectedDataList.Add(dataColumn.GetRecord_ID());
                                //}
                                Dictionary<int, decimal> prodQty = new Dictionary<int, decimal>();
                                prodQty.Add(Util.GetValueOfInt(dataColumn.GetRecord_ID()), Util.GetValueOfDecimal(data1));
                                VAdvantage.Classes.InfoLines pQty = new InfoLines();
                                pQty._AD_Session_ID = Envs.GetCtx().GetAD_Session_ID();
                                pQty._prodQty = prodQty;
                                pQty._windowNo = _WindowNo;
                                VAdvantage.Classes.InfoLines.PQ.Add(pQty);
                            }
                            else
                            {
                                log.Severe("For multiple selection, IDColumn should be key column for selection");
                            }
                        }
                    }
                }
            }

            if (selectedDataList.Count == 0)
            {
                object row = vdgvRecords.ItemsSource.OfType<object>().ToList()[0];

                if (vdgvRecords.SelectedItem != null)
                {
                    row = vdgvRecords.SelectedItem;
                }
                if (row != null && _keyColumnIndex != -1)
                {
                    object data = null;
                    var type = row.GetType();
                    PropertyInfo objPropInfo = type.GetProperty(_Layout[_keyColumnIndex].GetColHeader());
                    if (objPropInfo != null)
                    {
                        data = objPropInfo.GetValue(row, null);
                        if (data.GetType() == typeof(IDColumn))
                        {
                            selectedDataList.Add(((IDColumn)data).GetRecord_ID());
                        }
                        else if (data.GetType() == typeof(Int32))
                        {
                            selectedDataList.Add((int)data);
                        }
                    }
                }
            }

            return selectedDataList.ToArray();
        }
        /// <summary>
        /// Gets the selected key from the grid
        /// </summary>
        /// <returns></returns>
        public Object GetSelectedKey()
        {
            if (!_ok || _results.Count <= 0)
                return null;
            return _results[0];
        }

        ///// <summary>
        ///// Get selected Keys
        ///// </summary>
        ///// <returns>selected keys (Integers)</returns>
        //public List<int?> GetSelectedKeys()
        //{
        //    if (!_ok || _results.Count == 0)
        //    {
        //        return null;
        //    }
        //    return _results;

        //}

        /// <summary>
        /// Get selected Keys
        /// </summary>
        /// <created by>Raghu</created>
        /// <date>14-Dec-2011</date>
        /// <returns>selected keys (Integers)</returns>
        public Object[] GetSelectedKeys()
        {
            if (!_ok || _results.Count == 0)
            {
                return null;
            }
            return _results.ToArray();

        }

        //private List<int?> _results = new List<int?>(3);
        /// <summary>
        /// <Updatedby>Raghu</Updatedby>
        /// <date>14-Dec-2011</date>
        /// </summary>
        private System.Collections.ArrayList _results = new System.Collections.ArrayList(3);

        public virtual void SaveSelectionDetail()
        {
            //Comment by raghu 20-12-2010
            log.Config("OK=" + _ok);
            //if (!_ok)
            //{
            //    _results.Clear();
            //    vdgvRecords.ItemsSource = null;
            //    vdgvRecords = null;
            //    return;
            //}

            //var count = vdgvRecords.ItemsSource.OfType<object>().Count();
            //if (count == 0)
            //    return;

            //int? data = GetSelectedRowKey();
            //if (data != null)
            //    _results.Add(data);

            //log.Config(GetSelectedSQL());

            //SaveSelectionDetail();
            //vdgvRecords.ItemsSource = null;
            ////vdgvRecords = null;
        }

        /// <summary>
        /// Factory Constructor
        /// </summary>
        /// <param name="frame">parent form</param>
        /// <param name="modal">new window is modal</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="tableName">table name of the search</param>
        /// <param name="keyColumn">key column of the search</param>
        /// <param name="value">query value</param>
        /// <param name="multiSelection">multiSelection  allow to select more than one row</param>
        /// <param name="whereClause">whereClause fully qualified where clause for the search</param>
        /// <returns>special or general Info Window</returns>
        public static Info Create(ChildWindow frame, bool modal, int WindowNo,
            String tableName, String keyColumn, String value,
            bool multiSelection, String whereClause)
        {
            Info info = null;   //create an object of Info class
            Context ctx = Envs.GetContext();  //get the current context

            //business partner conditions
            if (tableName.Equals("C_BPartner"))
            {
                /*CR_01*/
                info = CreateInfoBPartner(frame, modal, WindowNo, value, ctx.IsSOTrx(), multiSelection, whereClause);
                //info = new InfoBPartner(frame, modal, WindowNo, value, ctx.IsSOTrx(), multiSelection, whereClause);
            }
            else if (tableName.Equals("M_Product"))
            {
                /*CR_01*/
                info = CreateInfoProduct(frame, modal, WindowNo, 0, 0, value, multiSelection, whereClause);
                //info = new InfoProduct(frame, modal, WindowNo, 0, 0, value, multiSelection, whereClause);
            }
            else if (tableName.Equals("C_Invoice"))
            {
                /*CR_01*/
                info = CreateOtherInfo("InfoInvoice", frame, modal, WindowNo, value, multiSelection, whereClause);
                //info = new InfoInvoice(frame, modal, WindowNo, value, multiSelection, whereClause);
            }
            else if (tableName.Equals("A_Asset"))
            {
                /*CR_01*/
                info = CreateInfoAssest(frame, modal, WindowNo, 0, value, multiSelection, whereClause);
                //info = new InfoAsset(frame, modal, WindowNo, 0, value, multiSelection, whereClause);
            }
            else if (tableName.Equals("C_Order"))
            {
                /*CR_01*/
                info = CreateOtherInfo("InfoOrder", frame, modal, WindowNo, value, multiSelection, whereClause);
                //info = new InfoOrder(frame, modal, WindowNo, value, multiSelection, whereClause);
            }
            else if (tableName.Equals("M_InOut"))
            {
                /*CR_01*/
                info = CreateOtherInfo("InfoInOut", frame, modal, WindowNo, value, multiSelection, whereClause);
                //info = new InfoInOut(frame, modal, WindowNo, value, multiSelection, whereClause);
            }
            else if (tableName.Equals("C_Payment"))
            {
                /*CR_01*/
                info = CreateOtherInfo("InfoPayment", frame, modal, WindowNo, value, multiSelection, whereClause);
                //info = new InfoPayment(frame, modal, WindowNo, value, multiSelection, whereClause);
            }
            else if (tableName.Equals("C_CashLine"))
            {
                /*CR_01*/
                info = CreateOtherInfo("InfoCashLine", frame, modal, WindowNo, value, multiSelection, whereClause);
                //info = new InfoCashLine(frame, modal, WindowNo, value, multiSelection, whereClause);
            }
            else if (tableName.Equals("S_ResourceAssigment"))
            {
                //not used in the window version
                //info = new InfoAssignment(frame, modal, WindowNo, value,multiSelection, whereClause);
            }
            else
            {
                /*CR_01*/
                info = CreateInfoGeneral(frame, modal, WindowNo, value, tableName, keyColumn, multiSelection, whereClause);
                //info = new InfoGeneral(frame, modal, WindowNo, value, tableName, keyColumn, multiSelection, whereClause);
            }
            //info.StartPosition = FormStartPosition.CenterScreen;

            return info;
        }


        #region CR_01

        private static Info CreateInfoGeneral(object frame, bool modal, int WindowNo, string QueryValue, string tableName, string keyColumn, bool multiSelection, string whereClause)
        {
            Type type = GetClass("InfoGeneral");
            if (type != null)
            {
                System.Reflection.ConstructorInfo constructor = null;
                try
                {
                    constructor = type.GetConstructor(new Type[] { typeof(Form), typeof(bool), typeof(int), typeof(String), typeof(String), typeof(String), typeof(bool), typeof(String) });
                }
                catch (Exception e)
                {
                    //log.Warning("No transaction Constructor for " + type.FullName + " (" + e.ToString() + ")");
                }
                if (constructor != null)
                {
                    try
                    {
                        return (Info)constructor.Invoke(new object[] { frame, modal, WindowNo,
                       QueryValue,tableName,keyColumn, multiSelection, whereClause});

                    }
                    catch
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            return null;
        }

        private static Info CreateInfoAssest(object frame, bool modal, int WindowNo, int p, string QueryValue, bool multiSelection, string whereClause)
        {
            Type type = GetClass("InfoAsset");
            if (type != null)
            {
                System.Reflection.ConstructorInfo constructor = null;
                try
                {
                    constructor = type.GetConstructor(new Type[] { typeof(Form), typeof(bool), typeof(int), typeof(int), typeof(String), typeof(bool), typeof(String) });
                }
                catch (Exception e)
                {
                    //log.Warning("No transaction Constructor for " + type.FullName + " (" + e.ToString() + ")");
                }
                if (constructor != null)
                {
                    try
                    {
                        return (Info)constructor.Invoke(new object[] { frame, modal, WindowNo,p,
                       QueryValue, multiSelection, whereClause});

                    }
                    catch
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            return null;
        }

        private static Info CreateOtherInfo(string clazzName, object frame, bool modal, int WindowNo, string QueryValue, bool multiSelection, string whereClause)
        {
            Type type = GetClass(clazzName);
            if (type != null)
            {
                System.Reflection.ConstructorInfo constructor = null;
                try
                {
                    constructor = type.GetConstructor(new Type[] { typeof(Form), typeof(bool), typeof(int), typeof(String), typeof(bool), typeof(String) });
                }
                catch (Exception e)
                {
                    //log.Warning("No transaction Constructor for " + type.FullName + " (" + e.ToString() + ")");
                }
                if (constructor != null)
                {
                    try
                    {
                        return (Info)constructor.Invoke(new object[] { frame, modal, WindowNo,
                       QueryValue, multiSelection, whereClause});

                    }
                    catch
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            return null;
        }

        private static Info CreateInfoProduct(object frame, bool modal, int WindowNo, int M_Warehouse_ID, int M_PriceList_ID, string QueryValue, bool multiSelection, string whereClause)
        {
            Type type = GetClass("InfoProduct");
            if (type != null)
            {
                System.Reflection.ConstructorInfo constructor = null;
                try
                {
                    constructor = type.GetConstructor(new Type[] { typeof(Form), typeof(bool), typeof(int), typeof(int), typeof(int), typeof(String), typeof(bool), typeof(String) });
                }
                catch (Exception e)
                {
                    //log.Warning("No transaction Constructor for " + type.FullName + " (" + e.ToString() + ")");
                }
                if (constructor != null)
                {
                    try
                    {
                        return (Info)constructor.Invoke(new object[] { frame, true, WindowNo,
                        M_Warehouse_ID,M_PriceList_ID,QueryValue, multiSelection, whereClause});

                    }
                    catch
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            return null;
        }

        private static Info CreateInfoBPartner(object frame, bool modal, int WindowNo, string QueryValue, bool isSOTrx, bool multiSelection, string whereClause)
        {
            Type type = GetClass("InfoBPartner");
            if (type != null)
            {
                System.Reflection.ConstructorInfo constructor = null;
                try
                {
                    constructor = type.GetConstructor(new Type[] { typeof(Form), typeof(bool), typeof(int), typeof(String), typeof(bool), typeof(bool), typeof(String) });
                }
                catch (Exception e)
                {
                    //g.Warning("No transaction Constructor for " + type.FullName + " (" + e.ToString() + ")");
                }
                if (constructor != null)
                {
                    try
                    {
                        return (Info)constructor.Invoke(new object[] { frame, true, WindowNo,
                        QueryValue, isSOTrx, false, whereClause});
                    }
                    catch
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            return null;
        }

        private static Type GetClass(string clazzName)
        {
            Type type = null;
            try
            {
                Assembly asm = Assembly.Load(GlobalVariable.PRODUCT_NAME);
                type = asm.GetType("ViennaAdvantage.Search." + clazzName);
            }
            catch
            {
            }
            if (type == null)
            {
                type = Type.GetType("VAdvantage.Search." + clazzName);
            }

            return type;
        }

        #endregion

        /// <summary>
        /// Show BPartner Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        public static void ShowBPartner(Object frame, int WindowNo)
        {
            Context ctx = Envs.GetContext();
            //Info info = new InfoBPartner(frame, false, WindowNo, "", ctx.IsSOTrx(), false, "");
            Info info = CreateInfoBPartner(frame, false, WindowNo, "", ctx.IsSOTrx(), false, "");
            info.Show();
            //AEnv.showCenterWindow(frame, info);
        }

        /// <summary>
        /// Show Product Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        public static void ShowProduct(Object frame, int WindowNo)
        {
            Info info = CreateInfoProduct(frame, false, WindowNo,
                Envs.GetCtx().GetContextAsInt(WindowNo, "M_Warehouse_ID"),
                Envs.GetCtx().GetContextAsInt(WindowNo, "M_PriceList_ID"),
                "",		//	value 
                false, "");


            //Info info = new InfoProduct(frame, false, WindowNo,
            //    Envs.GetCtx().GetContextAsInt(WindowNo, "M_Warehouse_ID"),
            //    Envs.GetCtx().GetContextAsInt(WindowNo, "M_PriceList_ID"),
            //    "",		//	value 
            //    false, "");
            info.Show();
            //AEnv.showCenterWindow(frame, info);
        }

        /// <summary>
        /// Show Asset Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        public static void ShowAsset(object frame, int WindowNo)
        {
            //Info info = new InfoAsset(frame, false, WindowNo,
            //    0, "", false, "");

            Info info = CreateInfoAssest(frame, false, WindowNo, 0, "", false, "");
            info.Show();
            //AEnv.showCenterWindow(frame, info);
        }

        /// <summary>
        /// Show Order Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="value">value</param>
        public static void ShowOrder(object frame, int WindowNo, String value)
        {
            //Info info = new InfoOrder(frame, false, WindowNo, value,
            //    false, "");
            Info info = CreateOtherInfo("InfoOrder", frame, false, WindowNo, value, false, "");


            info.Show();//
            //AEnv.showCenterWindow(frame, info);
        }

        /// <summary>
        /// Show Invoice Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="value">value</param>
        public static void ShowInvoice(object frame, int WindowNo, String value)
        {
            Info info = new InfoInvoice(frame, false, WindowNo, value,
                false, "");
            info.Show();
            //AEnv.showCenterWindow(frame, info);
        }

        /// <summary>
        /// Show Shipment Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="value">value</param>
        public static void ShowInOut(object frame, int WindowNo, String value)
        {
            //Info info = new InfoInOut(frame, false, WindowNo, value,
            //    false, "");
            Info info = CreateOtherInfo("InfoInOut", frame, false, WindowNo, value, false, "");

            info.Show();
            //AEnv.showCenterWindow(frame, info);
        }

        /// <summary>
        /// Show Payment Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="value">value</param>
        public static void ShowPayment(object frame, int WindowNo, String value)
        {
            Info info = CreateOtherInfo("InfoPayment", frame, false, WindowNo, value, false, "");
            //Info info = new InfoPayment(frame, false, WindowNo, value,
            //    false, "");
            info.Show();
            //AEnv.showCenterWindow(frame, info);
        }

        /// <summary>
        /// Show Assignment  Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="value">value</param>
        public static void ShowCashLine(object frame, int WindowNo, String value)
        {
            Info info = CreateOtherInfo("InfoCashLine", frame, false, WindowNo, value, false, "");
            //Info info = new InfoCashLine(frame, false, WindowNo, value,
            //    false, "");
            info.Show();
            //AEnv.showCenterWindow(frame, info);
        }

        /// <summary>
        /// Show Assignment  Info (non modal)
        /// </summary>
        /// <param name="frame">Parent Frame</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="value">value</param>
        public static void ShowAssignment(object frame, int WindowNo, String value)
        {
            //Info info = new InfoAssignment(frame, false, WindowNo, value,
            //    false, "");
            //info.ShowDialog();
            //AEnv.showCenterWindow(frame, info);
        }

        private String GetKeyColumn()
        {
            return _keyColumn;
        }   //  getKeyColumn


        /// <summary>
        /// Save Selection	- Called by dispose
        /// </summary>
        public void SaveSelection()
        {
            log.Config("OK=" + _ok);
            if (!_ok)
            {
                _results.Clear();
                vdgvRecords.ItemsSource = null;
                //vdgvRecords = null;
                return;
            }
            var count = 0;

            if (vdgvRecords.ItemsSource != null)
            {
                count = vdgvRecords.ItemsSource.OfType<object>().Count();
            }

            if (count == 0)
                return;


            if (_multiSelection)
            {
                _results.AddRange(GetSelectedRowKeys());
            }

            else
            {
                int? data = GetSelectedRowKey();
                if (data != null)
                    _results.Add(data);
            }

            log.Config(GetSelectedSQL());

            SaveSelectionDetail();
            vdgvRecords.ItemsSource = null;
        }



        /// <summary>
        /// Get where clause for (first) selected key ListBoxVO
        /// </summary>
        /// <returns>WHERE Clause</returns>
        public String GetSelectedSQL()
        {
            StringBuilder sb = new StringBuilder(GetKeyColumn());
            try
            {
                //	No results
                //int?[] keys = GetSelectedKeys().ToArray();
                object[] keys = GetSelectedKeys();
                if (keys == null || keys.Length == 0)
                {
                    log.Config("No Results - OK="
                        + _ok + ", Cancel=" + _cancel);
                    return "";
                }
                //

                if (keys.Length > 1)
                {
                    sb.Append(" IN (");
                }
                else
                {
                    sb.Append("=");
                }

                //	Add elements
                for (int i = 0; i < keys.Length; i++)
                {
                    if (GetKeyColumn().EndsWith("_ID"))
                    {
                        sb.Append(keys[i].ToString());
                        if (i < keys.Length - 1)
                        {
                            sb.Append(",");
                        }
                    }
                    else
                    {
                        sb.Append("'").Append(keys[i].ToString());
                        if (i < keys.Length - 1)
                        {
                            sb.Append(",");
                        }
                    }
                }
                //sb.replace(sb.length() - 1, sb.length(), "");
                //sb.Replace(",", "");

                if (keys.Length > 1)
                {
                    sb.Append(")");
                    //str += ")";
                }
            }
            catch
            {
                return "";
            }
            return sb.ToString();
        }

        /// <summary>
        /// Loaded correctly
        /// </summary>
        /// <returns>true if loaded OK</returns>
        public bool LoadedOK()
        {
            return _LoadedOK;
        }

        public virtual void Init()
        {
            InitializeComponent();
            outerPanel.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            //Grid.SetRow(tablePanel, 0);
            //Grid.SetColumn(tablePanel, 0);
            //outerPanel.Children.Add(tablePanel);
            //tablePanel.Margin = new Thickness(3, 3, 3, 3);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="from"></param>
        /// <param name="staticWhere"></param>
        /// <param name="orderBy"></param>
        protected void PrepareTable(String from, String staticWhere, String orderBy)
        {
            _Layout = GetInfoColumns();
            ModelValidationEngine mve = ModelValidationEngine.Get();
            int AD_Client_ID = Envs.GetContext().GetAD_Client_ID();
            List<Info_Column> columns = new List<Info_Column>();

            for (int i = 0; i < _Layout.Length; i++)
            {
                if (_Layout[i].GetColHeader().Contains("/"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("/", " "));                  
                }
                if (_Layout[i].GetColHeader().Contains("-"))
                {                 
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("-", " "));
                }
                if (_Layout[i].GetColHeader().Contains("#"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("#", " "));
                }
                if (_Layout[i].GetColHeader().Contains("@"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("@", " "));
                }
                if (_Layout[i].GetColHeader().Contains("!"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("!", " "));
                }
                if (_Layout[i].GetColHeader().Contains("$"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("$", " "));
                }
                if (_Layout[i].GetColHeader().Contains("^"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("^", " "));
                }
                if (_Layout[i].GetColHeader().Contains("&"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("&", " "));
                }
                if (_Layout[i].GetColHeader().Contains("*"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("*", " "));
                }
                if (_Layout[i].GetColHeader().Contains("%"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("%", " "));
                }
                if (_Layout[i].GetColHeader().Contains("."))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace(".", " "));
                }
                if (_Layout[i].GetColHeader().Contains(">"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace(">", " "));
                }
                if (_Layout[i].GetColHeader().Contains("<"))
                {
                    _Layout[i].SetColHeader(_Layout[i].GetColHeader().ToString().Replace("<", " "));
                }

                columns.Add(_Layout[i]);
            }

            StringBuilder sqlFrom = new StringBuilder(from);
            StringBuilder sqlOrder = new StringBuilder(orderBy);
            bool change = mve.UpdateInfoColumns(AD_Client_ID, columns, sqlFrom, sqlOrder);

            if (change)
            {
                from = sqlFrom.ToString();
                orderBy = sqlOrder.ToString();
                _Layout = new Info_Column[columns.Count()];
                _Layout = columns.ToArray();
                //Array.Sort(_Layout);
            }

            //vdgvRecords.Columns.Add(
            // clear and unbind the grid
            vdgvRecords.ItemsSource = null;
            //vdgvRecords.DataBindings.Clear();
            vdgvRecords.Columns.Clear();
            //vdgvRecords.DoubleClick += new EventHandler(vdgvRecords_DoubleClick);


            StringBuilder sql = new StringBuilder("SELECT ");
            for (int i = 0; i < _Layout.Length; i++)
            {
                if (i > 0)
                    sql.Append(", ");
                sql.Append(_Layout[i].GetColSQL());
                if (_Layout[i].IsIDcol())
                    sql.Append(",").Append(_Layout[i].GetIDcolSQL());

                if (_Layout[i].IsColorColumn())
                {
                }
                //p_table.setColorColumn(i);
                if (_Layout[i].GetColClass() == typeof(IDColumn))
                    _keyColumnIndex = i;
            }

            //vdgvRecords.Columns[0].Visible = false;

            sql.Append(" FROM ").Append(from);
            //
            sql.Append(" WHERE ").Append(staticWhere);
            _sqlMain = sql.ToString();
            _sqlCount = "SELECT COUNT(*) FROM " + from + " WHERE " + staticWhere;
            //
            _sqlOrder = "";
            if (orderBy != null && orderBy.Length > 0)
                _sqlOrder = " ORDER BY " + orderBy;

            if (_keyColumnIndex == -1)
                log.Log(Level.SEVERE, "No KeyColumn - " + sql.ToString());

        }

        /// <summary>
        /// Gets the table name
        /// </summary>
        /// <returns></returns>
        public String GetTableName()
        {
            return _tableName;
        }   //  getTableName


        public abstract String GetSQLWhere();

        public abstract void SetParameters(out SqlParameter[] param, bool forCount);

        Thread worker = null;
        SqlParameter[] param = null;


        /// <summary>
        /// Executes the final query
        /// </summary>
        public void ExecuteQuery()
        {
            //Size canvasSize = .NewSize;
            //Canvas.SetTop(BusyWindow, ((canvasSize.Height / 2) - (BusyWindow.Height / 2)));
            //Canvas.SetLeft(BusyWindow, ((canvasSize.Width / 2) - (BusyWindow.Width / 2)));

            ThreadPool.QueueUserWorkItem(delegate
            {
                if (!TestCount())
                    return;

                //Run();
                worker = new Thread(new ThreadStart(this.Run));
                worker.CurrentCulture = VAdvantage.Utility.Envs.GetLanguage(VAdvantage.Utility.Envs.GetContext()).GetCulture(VAdvantage.Utility.Envs.GetLoginLanguage(VAdvantage.Utility.Envs.GetContext()).GetAD_Language());
                worker.CurrentUICulture = VAdvantage.Utility.Envs.GetLanguage(VAdvantage.Utility.Envs.GetContext()).GetCulture(VAdvantage.Utility.Envs.GetLoginLanguage(VAdvantage.Utility.Envs.GetContext()).GetAD_Language());
                //this.Cursor = Cursors.Wait;
                SetStatusMsg("Start Search...");
                worker.IsBackground = true;
                worker.Start();
            });
        }

        /// <summary>
        /// Test Row Count
        /// </summary>
        /// <returns>true if display</returns>
        private bool TestCount()
        {
            long start = CommonFunctions.CurrentTimeMillis();
            //DispatcherOperation op = Dispatcher.BeginInvoke(
            String dynWhere = GetSQLWhere();
            StringBuilder sql = new StringBuilder(_sqlCount);
            if (dynWhere.Length > 0)
                sql.Append(dynWhere);   //  includes first AND
            String countSql = Msg.ParseTranslation(Envs.GetContext(), sql.ToString());	//	Variables
            if (countSql.IndexOf("param") != -1 && countSql.IndexOf("@param") == -1 || countSql.IndexOf("@param") != -1)
            {
                countSql = countSql.Replace("@param", "param");
                countSql = countSql.Replace("param", "@param");
            }

            if (string.IsNullOrEmpty(countSql))
                return false;

            countSql = MRole.GetDefault().AddAccessSQL(countSql, GetTableName(),
                MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);
            log.Finer(countSql);
            int no = -1;
            try
            {
                //PreparedStatement pstmt = DB.prepareStatement(countSql, null);

                SetParameters(out param, true);
                IDataReader dr = DB.ExecuteReader(countSql, param);
                while (dr.Read())
                {
                    no = Util.GetValueOfInt(dr[0].ToString());
                }
                dr.Close();
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, countSql, e);
                //ErrorLog.FillErrorLog("Info.TestCount()", countSql, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
                no = -2;
            }
            log.Fine("#" + no.ToString() + " - " + (CommonFunctions.CurrentTimeMillis() - start) + "ms");
            //VAdvantage.Common. ("#" + no + " - " + (System.currentTimeMillis() - start) + "ms");
            if (no > 1000)
                return true; // ShowMessage.Ask("InfoHighRecordCount", true, no.ToString());
            return true;
        }	//	testCount


        public IEnumerable<IDictionary> GenerateData(DataSet ds)
        {
            if (ds == null)
            {
                //log.Log(Level.SEVERE, dataSql, "");
            }
            else
            {
                for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    int colOffset = 0;  //  columns start with 1
                    var dict = new Dictionary<string, object>();
                    for (int col = 0; col < _Layout.Length; col++)
                    {

                        try
                        {
                            Object data = null;
                            Type c = _Layout[col].GetColClass();
                            int colIndex = col + colOffset;
                            //if (col == 0)
                            //    _Layout[col].SetColHeader(_Layout[col].GetColHeader() + "_ID");

                            String colName = _Layout[col].GetColHeader();
                            if (c == typeof(IDColumn))
                            {
                                data = new IDColumn(Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex].ToString()));
                            }
                            else if (c == typeof(Boolean))
                            {
                                Object bl = ds.Tables[0].Rows[i][colIndex];
                                if (bl == null)
                                    data = false;
                                else
                                    data = "Y".Equals(bl.ToString());
                            }
                            else if (c == typeof(DateTime))
                            {
                                if (ds.Tables[0].Rows[i][colIndex] == null)
                                {
                                    data = null;
                                }
                                else
                                {
                                    if (ds.Tables[0].Rows[i][colIndex].ToString() != "")
                                    {
                                        data = DateTime.Parse(ds.Tables[0].Rows[i][colIndex].ToString());
                                    }
                                    else
                                    {
                                        data = null;
                                    }
                                }
                            }
                            else if (c == typeof(Decimal))
                            {
                                data = Util.GetValueOfDecimal(ds.Tables[0].Rows[i][colIndex].ToString());
                            }
                            else if (c == typeof(Double))
                            {
                                data = Util.GetValueOfDecimal(ds.Tables[0].Rows[i][colIndex].ToString());
                            }
                            else if (c == typeof(Int32))
                            {
                                data = Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex].ToString());
                            }
                            else if (c == typeof(KeyNamePair))
                            {
                                Object display = null;
                                if (ds.Tables[0].Rows[i][colIndex] != null)
                                    display = ds.Tables[0].Rows[i][colIndex].ToString();
                                else
                                    display = "";

                                int KeyValue = ds.Tables[0].Rows[i][colIndex + 1] == null ? 0 : Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex + 1].ToString());
                                int key = display != "" ? KeyValue : 0;
                                data = new KeyNamePair(key, display.ToString());
                                colOffset++;
                            }
                            else
                            {
                                if (ds.Tables[0].Rows[i][colIndex] != null)
                                    data = ds.Tables[0].Rows[i][colIndex].ToString();
                                else
                                    data = "";
                            }

                            dict[colName] = data;       //finally add data to enumerable dictionary
                        }
                        catch
                        {
                        }

                    }

                    yield return dict;
                }
            }
        }


        public void Run()
        {
            Dispatcher.BeginInvoke(delegate
            {
                BusyWindow.IsBusy = true;

            });
            long start = CommonFunctions.CurrentTimeMillis();
            String dynWhere = GetSQLWhere();
            StringBuilder sql = new StringBuilder(_sqlMain);
            if (dynWhere.Length > 0)
                sql.Append(dynWhere);   //  includes first AND

            sql.Append(_sqlOrder);
            String dataSqlStr = Msg.ParseTranslation(Envs.GetContext(), sql.ToString());	//	Variables

            if (dataSqlStr.IndexOf("param") != -1 && dataSqlStr.IndexOf("@param") == -1 || dataSqlStr.IndexOf("@param") != -1)
            {
                dataSqlStr = dataSqlStr.Replace("@param", "param");
                dataSqlStr = dataSqlStr.Replace("param", "@param");
            }


            dataSqlStr = MRole.GetDefault().AddAccessSQL(dataSqlStr, GetTableName(),
                            MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);

            String dataSql = dataSqlStr;
            log.Finer(dataSql);

            try
            {

                log.Finer("Start query - " + (CommonFunctions.CurrentTimeMillis() - start) + "ms");
                SetParameters(out param, true);//add by raghu//17-11-2010
                DataSet ds = DB.ExecuteDataset(dataSql.ToString(), param);
                log.Finer("End query - " + (CommonFunctions.CurrentTimeMillis() - start) + "ms");



                if (Dispatcher.CheckAccess())
                {
                    vdgvRecords.ItemsSource = GenerateData(ds).ToDataSource();
                    vdgvRecords.IsReadOnly = true;

                    if (vdgvRecords.Columns.Count > 0)
                        vdgvRecords.Columns[0].Visibility = System.Windows.Visibility.Collapsed;
                    BusyWindow.IsBusy = false;

                }
                else
                {
                    SetStatusMsg(ds.Tables[0].Rows.Count() + " " + Msg.GetMsg(Envs.GetContext(), "SearchRows_EnterQuery"));
                    Dispatcher.BeginInvoke(delegate
                    {
                        try
                        {
                            if (_keyColumn.ToUpper() == "M_PRODUCT_ID" && viewProd)
                            {

                            }

                            vdgvRecords.ItemsSource = GenerateData(ds).ToDataSource();
                          

                            if (_keyColumn.ToUpper() != "M_PRODUCT_ID")
                            {
                                vdgvRecords.IsReadOnly = true;
                            }

                            if (vdgvRecords.Columns.Count > 0)
                            {
                                vdgvRecords.Columns[0].Visibility = System.Windows.Visibility.Collapsed;

                                try
                                {
                                    if (_multiSelection)
                                    {
                                        vdgvRecords.Columns[1].IsReadOnly = false;
                                        vdgvRecords.Columns[1].Visibility = System.Windows.Visibility.Visible;
                                    }
                                    else
                                    {
                                        vdgvRecords.Columns[1].IsReadOnly = true;
                                        vdgvRecords.Columns[1].Visibility = System.Windows.Visibility.Collapsed;
                                    }
                                }
                                catch { }
                            }

                            BusyWindow.IsBusy = false;
                        }
                        catch { }
                    });
                }
            }
            catch
            {
                Dispatcher.BeginInvoke(delegate
                   {
                       BusyWindow.IsBusy = false;
                   });
            }

        }

        protected void SetBusy(bool val)
        {

            this.Cursor = val ? Cursors.Wait : Cursors.Arrow;
            busyWindow.Visibility = val ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;

            txtBusy.Visibility = val ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            if (val)
            {
                txtBusy.Text = Utility.Msg.GetMsg(Utility.Envs.GetCtx(), "Processing");
            }
            else
            {
                txtBusy.Text = "";
            }
        }

        private int _PO_Window_ID = -1;
        private int _SO_Window_ID = -1;

        /// <summary>
        /// Gets the window id
        /// </summary>
        /// <param name="tableName">name of the table</param>
        /// <param name="isSOTrx"></param>
        /// <returns>ad window id</returns>
        protected int GetAD_Window_ID(String tableName, bool isSOTrx)
        {
            if (!isSOTrx && _PO_Window_ID > 0)
                return _PO_Window_ID;
            if (_SO_Window_ID > 0)
                return _SO_Window_ID;
            //
            String sql = "SELECT AD_Window_ID, PO_Window_ID FROM AD_Table WHERE TableName=@tablename";
            try
            {
                SqlParameter[] param = new SqlParameter[1];
                param[0] = new SqlParameter("@tablename", tableName);

                IDataReader dr = DB.ExecuteReader(sql, param);
                while (dr.Read())
                {
                    _SO_Window_ID = Util.GetValueOfInt(dr[0].ToString());
                    _PO_Window_ID = Util.GetValueOfInt(dr[1].ToString());
                }
                dr.Close();
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
            }

            if (!isSOTrx && _PO_Window_ID > 0)
                return _PO_Window_ID;
            return _SO_Window_ID;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {

            _cancel = true;
            SaveSelection();
            VAdvantage.Classes.InfoLines.PQ.Clear();
            this.DialogResult = false;
            //base.Close();
        }





        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            VAdvantage.Classes.InfoLines.PQ.Clear();
            //if (!_cancel)
            //{
            //    _cancel = true;
            //    SaveSelection();
            //    base.Close();
            //}
        }

        /// <summary>
        /// Is cancelled?
        /// - if pressed Cancel = true
        /// - if pressed OK or window closed = false
        /// </summary>
        /// <returns>true if cancelled</returns>
        public bool IsCancelled()
        {
            return _cancel;
        }

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        public Grid tablePanel
        {
            get
            {
                return this.tablePanel1;
            }
        }

        public Grid outerPanel
        {
            get
            {
                return this.outerPanel1;
            }
        }

        public DataGrid vdgvRecords
        {
            get
            {
                return this.vdgvRecords1;
            }
        }
    }
}

